package edu.cu.cs214.hw9.controller;

import java.io.StringWriter;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import edu.cmu.cs214.hw9.json.*;
import edu.cmu.cs214.hw9.db.Constants;
/**
 * A controller to be used during the Registration Process
 * @author davidzheng
 *
 */
public class RegisterController extends AbstractController {
	/**
	 * Constructs Controller.  passes window so we can use JOptionPane
	 * @param window the controller's window
	 */
	public RegisterController(JFrame window)
	{
		super(window);
	}
	/**
	 * Attempts to Register the user
	 * @param username the user's name
	 * @param password the password
	 * @param password2 the confirm password entry
	 * @param email the user's email
	 * @return true on success, false on failure
	 */
	public boolean register(String username, String password, String password2, String email){
		//do checks that don't require a connection, so that we won't open it unless we have to
		if (!checkEmpty(username, password, password2, email)) return false;
		if (!checkMatch(password,password2)) return false;
		if (!checkValid(email)) return false;
		try{
			openConnection(Constants.SERVER_PORT0);  // EDITED FOR SHARDING
			
			out.println("EXISTS "+email); //send message to check if user exists
			if(in.readLine().equals("true")) //if response is true
			{
				JOptionPane.showMessageDialog(window, "Email Already Exists",
						"Registration Failure", JOptionPane.PLAIN_MESSAGE);
				out.println("END");
				closeConnection();
				return false;
			}
			
			//This portion is copied/modified from staff code, due to near identicalness
			//of function
			
			StringWriter myWriter = new StringWriter();
			JSONWriter jsonW = new JSONWriter(myWriter);
			jsonW.object();//start object (refer to JSONWriter javadoc for a more in depth explanation of creation)
				jsonW.key("username");//key
					jsonW.value(username);//value at key
				jsonW.key("password");//key
					jsonW.value(password);//value at key
				jsonW.key("email");
					jsonW.value(email);
			jsonW.endObject();//finish object
			String message = myWriter.toString();//creates a string serializing the object
			out.println("STORE "+message);//send the JSON to the server, along with a request to STORE it.
			System.out.println(in.readLine());
			out.println("END");
			closeConnection();
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * Checks for a valid email address.  Very basic, just makes sure there
	 * is a @.  Also makes sure there is no ":", because ":" is a crucial
	 * character in our message formats, so it would interfere with messages
	 * and crash the program
	 * @param email the email address to check for validity
	 * @return whether it is valid
	 */
	private boolean checkValid(String email) {
		if (email.contains("@") && !email.contains(":")) return true;
		else 
		{
			JOptionPane.showMessageDialog(window, "Invalid Email.  Must contain \"@\" and not \":\"",
					"Registration Failure", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
	}
	/**
	 * Helper method to check if the passwords match
	 * @param password1 password
	 * @param password2 confirm password
	 * @return true if they do match
	 */
	private boolean checkMatch(String password1, String password2) {
		if (password1.compareTo(password2) == 0)
			return true;
		else
		{
			JOptionPane.showMessageDialog(window, "Passwords don't match",
					"Registration Failure", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
	}
	/**
	 * Helper method to check that all fields are non-empty
	 * @param username
	 * @param password
	 * @param password2
	 * @param email
	 * @return true if this is the case
	 */
	private boolean checkEmpty(String username, String password, String password2,
			String email) {
		if (!(username.isEmpty()||password.isEmpty()||password2.isEmpty()||email.isEmpty()))
			return true;
		else
		{
			JOptionPane.showMessageDialog(window, "Empty inputs not allowed",
					"Registration Failure", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
	}
}
